<template>
    <div>
        <van-nav-bar title="修改地址" left-arrow @click-left="$router.go(-1)" />
        <van-address-edit :area-list="areaList" show-delete show-set-default show-search-result
            :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave"
            @delete="onDelete" @change-detail="onChangeDetail" :address-info="adsinfo" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { areaList } from '@vant/area-data'
import { GetUserAds } from '@/api/api'
import { useRoute } from 'vue-router'
import { AddAress } from '@/Hooks/addadress'
import { DeleteAddress } from '@/api/api';
import { showToast } from 'vant';
import router from '@/router';

const route = useRoute()
const adsid = route.query.id
const adsinfo = ref({})
const searchResult = ref([])
const { toSave } = AddAress()


//获取地址列表
const getadlist = async () => {
    const params = {
        userid: localStorage.getItem('userId')
    }
    const res = await GetUserAds(params)
    // console.log(res);
    if (res.data.code === '200') {
        const t = res.data.data.filter((item: any) => {
            return item.addressid == adsid
        })
        // console.log(t);
        adsinfo.value = {
            addressDetail: t[0].addressDetail,
            city: t[0].city,
            county: t[0].county,
            province: t[0].province,
            name: t[0].name,
            tel: t[0].tel,
            isDefault: t[0].isDefault,
        }
    }

}

onMounted(() => {
    getadlist()
})
const onSave = async (e: any) => {
    //先删除
    const result = await DeleteAddress({ addressid: adsid })
    // console.log(result);
    if (result.data.code === '200') {
        //后添加
        toSave(e)
    } else {
        showToast({
            message: '保存失败',
            position: 'middle'
        })
    }

}
const onDelete = async () => {//删除地址
    const resdelet = await DeleteAddress({ addressid: adsid })
    // console.log(resdelet);
    if (resdelet.data.code === '200') {
        showToast({
            message: '删除成功',
            position: 'middle'
        })
        router.back()
    }
}
const onChangeDetail = () => {

}

</script>

<style lang="scss" scoped></style>